package cn.farm.farm.login.Controller;

import cn.farm.farm.Aop.IsLogin;
import cn.farm.farm.Config.Common.CommonDto.*;
import cn.farm.farm.Config.Common.CommonEnums.*;
import cn.farm.farm.Config.Common.CommonException.DefaultException;
import cn.farm.farm.Config.Common.CommonException.NoPhotoException;
import cn.farm.farm.Config.Common.CommonException.NotFoundException;
import cn.farm.farm.Entity.Common.TpRegion2;
import cn.farm.farm.Entity.Common.User;
import cn.farm.farm.Service.CommonService.AddressService;
import cn.farm.farm.Service.CommonService.OrdinaryService;
import cn.farm.farm.Service.CommonService.RegistService;
import cn.farm.farm.Service.CommonService.UserModifyService;
import cn.farm.farm.Util.file.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

//import org.apache.catalina.servlet4preview.http.HttpServletRequest;

@RestController
@EnableAutoConfiguration
@RequestMapping("farm/common")
public class CommonController {
    @Autowired
    private OrdinaryService ordinaryService;
    @Autowired
    private RegistService registService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private UserModifyService userModifyService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @RequestMapping("/loginout")
    public Result login(
            @RequestParam(value = "phone") String phone
    ){
        Result result;//返回信息
        LoginOutExecution execution;//返回Data
        request.getSession().removeAttribute("user");
        execution = new LoginOutExecution(LoginOutStateEnum.SUCCESS);
        result = new Result(execution.getState(), execution.getStateInfo());
        return result;

    }
//consumer写
    //获取当前session中用户的信息
    @RequestMapping("/get/user")
    public Result<SessionExecution> getUser(){
        Result<SessionExecution> result;//返回信息
        SessionExecution execution;//返回Data
        User user = null;

        try {
            user = (User)request.getSession().getAttribute("user");
            if(user == null){
                throw new DefaultException("session已过期或未登录");
            }
            execution = new SessionExecution(SessionStateEnum.SUCCESS);
            result = new Result(execution.getState(),user,execution.getStateInfo());
            return result;
        }catch (DefaultException d){
            execution = new SessionExecution(SessionStateEnum.DEFAULT);
            result = new Result(execution.getState(),user,execution.getStateInfo());
            return result;
        }catch (Exception e){
            execution = new SessionExecution(SessionStateEnum.INNER_ERROR);
            result = new Result(execution.getState(),user,execution.getStateInfo());
            return result;
        }
    }

    @RequestMapping(value = "/login" ,produces = "application/problem+json;charset=UTF-8")
    public Result<loginExecution> login(
            @RequestParam(value = "phone")String phone,
            @RequestParam(value = "password")String password
    ) {
        Result<loginExecution> result;//返回信息
        loginExecution execution;//返回Data
        User user;
        HttpSession session = request.getSession();       // 获取Session对象

        try {
            user = ordinaryService.select(phone, password);
            session.setAttribute("user", user);// 设置Session中的属性
            session.setMaxInactiveInterval(60*60*2);//设置失效时间为2小时
            execution = new loginExecution(loginStateEnum.SUCCESS);
            result = new Result(execution.getState(), user, execution.getStateInfo());
            return result;
        } catch (DefaultException e1) {
            execution = new loginExecution(loginStateEnum.DEFAULT);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }
    }

    //普通用户注册
    @RequestMapping("ordinary/regist")
    public Result<RegistExecution> regist(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "nickname") String nickname,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "email") String email,
            @RequestParam(value = "address") Integer address,
            @RequestParam(value = "postcode") String postcode,
            @RequestParam(value = "introduction") String introduction,
            @RequestParam(value = "state") Integer state,
            @RequestParam(value = "role") Integer role
    ){
        Result<RegistExecution> result;//返回信息
        RegistExecution execution;//返回Data
       // User user = null;
        try {
            registService.regist(name, password, nickname, phone, email, address, postcode, introduction, state, role);
            execution = new RegistExecution(RegistStateEnum.SUCCESS);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        } catch (DefaultException e1) {
            execution = new RegistExecution(RegistStateEnum.DEFAULT);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        } catch (Exception e) {
            execution = new RegistExecution(RegistStateEnum.INNER_ERROR);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }
    }

    //专家用户注册
    @RequestMapping("expert/regist")
    public Result<RegistExecution> ExprtRegist(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "nickname") String nickname,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "email") String email,
            @RequestParam(value = "address") Integer address,
            @RequestParam(value = "postcode") String postcode,
            @RequestParam(value = "introduction") String introduction,
            @RequestParam(value = "state") Integer state,
            @RequestParam(value = "role") Integer role
    ){
        Result<RegistExecution> result;//返回信息
        RegistExecution execution;//返回Data
        User user = null;
        try {
            registService.ExpertRegist(name, password, nickname, phone, email, address, postcode, introduction, state, role);
            execution = new RegistExecution(RegistStateEnum.EXPERT_SUCCESS);
            result = new Result(execution.getState(), user, execution.getStateInfo());
            return result;
        } catch (DefaultException e1) {
            execution = new RegistExecution(RegistStateEnum.DEFAULT);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        } catch (Exception e) {
            execution = new RegistExecution(RegistStateEnum.INNER_ERROR);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }
    }

    //省市县三级联动
    @RequestMapping("/linkage")
    public Result<List<TpRegion2>> linkage(
            @RequestParam(value = "level") Integer level,               //当前省市县等级
            @RequestParam(value = "parentId") Integer parentId          //id
    ) {
        Result<List<TpRegion2>> result;//返回信息
        AddressExecution execution;//返回Data
        List<TpRegion2> list;
        list = addressService.found(level, parentId);
        execution = new AddressExecution(AddressStateEnum.SUCCESS);
        result = new Result(execution.getState(), list, execution.getStateInfo());
        return result;
    }

    //个人信息修改
    @RequestMapping("/user/modify")
    @IsLogin
    public Result userModify(
            HttpSession session,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "nickname") String nickname,
            @RequestParam(value = "email") String email,
            @RequestParam(value = "postcode") String postcode,
            @RequestParam(value = "introduction") String introduction
    ) {
        Result result;//返回信息
        UserModifyExecution execution;//返回Data
        try {
            User user1 = (User)request.getSession().getAttribute("user");
            int userid = user1.getUserid();
            User user = userModifyService.modify(userid,name, nickname, email,  postcode, introduction);
            request.getSession().setAttribute("user", user);
            execution = new UserModifyExecution(UserModifyEnum.SUCCESS);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        } catch (Exception e) {
            execution = new UserModifyExecution(UserModifyEnum.INNER_ERROR);
            result = new Result(execution.getState(), e.getMessage());
            return result;
        }

    }

    //修改密码(先确定已经使用)
    @RequestMapping(value = "/user/password")
    @IsLogin
    public Result password(
            HttpSession session,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "userid") Integer userid
    ){
        Result result;//返回信息
        PasswordExecution execution;//返回Data
        try {
            User user = (User) request.getSession().getAttribute("user");
            userModifyService.modifyPassword(user.getUserid(), password);//不需要返回值
            request.getSession().setAttribute("user",user);
            execution = new PasswordExecution(PasswordStateEnum.SUCCESS);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }catch (NotFoundException n){
            execution = new PasswordExecution(PasswordStateEnum.DEFAULT);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }catch (Exception e) {
            execution = new PasswordExecution(PasswordStateEnum.INNER_ERROR);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }
    }

    //修改绑定电话
    @RequestMapping(value = "/user/phone")
    @IsLogin
    public Result phone(
            HttpSession session,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "userid") Integer userid
    ){
        Result result;//返回信息
        PhoneExecution execution;//返回Data
        try {
            User user = (User)request.getSession().getAttribute("user");
            userModifyService.modifyPhone(user.getUserid(), phone);//不需要返回值
            user.setPhone(phone);
            request.getSession().setAttribute("user",user);
            execution = new PhoneExecution(PhoneStateEnum.SUCCESS);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        } catch (DefaultException n){
            execution = new PhoneExecution(PhoneStateEnum.DEFAULT);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }catch (Exception e) {
            execution = new PhoneExecution(PhoneStateEnum.INNER_ERROR);
            result = new Result(execution.getState(), execution.getStateInfo());
            return result;
        }
    }

    //修改用户头像
    @RequestMapping(value = "/user/modifyphoto")
    @IsLogin
    public Result ModifyUserPhoto(
            HttpSession session,
            @RequestParam(value = "photo") MultipartFile photo//pageNum,pageSize
    ) {
        Result result;
        PhotoExecution execution;
        User user = (User) request.getSession().getAttribute("user");
        try {
            if (photo != null) {
                String photoPath = OssUtil.uploadImage(photo);
                userModifyService.ModifyPhoto(user.getUserid(),photoPath);
                user.setPhoto(photoPath);
            }else{
                //上传图片为空，报图片空异常
                throw new NoPhotoException("图片为空");
            }
            execution = new PhotoExecution(PhotoStateEnum.SUCCESS);
            result = new Result(execution.getState(),execution.getStateInfo());
            request.getSession().setAttribute("user",user);
            return result;
        }catch (DefaultException e){
            execution = new PhotoExecution(PhotoStateEnum.DEFAULT);
            result = new Result(execution.getState(),execution.getStateInfo());
            return result;
        }catch (Exception e){
            execution = new PhotoExecution(PhotoStateEnum.INNER_ERROR);
            result = new Result(execution.getState(),e.getMessage());
            return result;
        }
    }
}
